<template>
  <div class="process-capability-analysis" v-loading="loading">
    <el-row :gutter="20">
      <!-- 过程能力汇总卡片 -->
      <el-col :span="24">
        <el-card shadow="hover" class="capability-card">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="8" :md="8">
              <div class="capability-item">
                <div class="item-title">Cp值 (过程能力指数)</div>
                <div class="item-value" :class="getCpClass">{{ capabilityData.capability?.cp || 'N/A' }}</div>
                <div class="item-desc">{{ capabilityData.capabilityInterpretation?.cp || '' }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8">
              <div class="capability-item">
                <div class="item-title">Cpk值 (过程能力指数)</div>
                <div class="item-value" :class="getCpkClass">{{ capabilityData.capability?.cpk || 'N/A' }}</div>
                <div class="item-desc">{{ capabilityData.capabilityInterpretation?.cpk || '' }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8">
              <div class="capability-item">
                <div class="item-title">总体评价</div>
                <div class="item-desc">{{ capabilityData.capabilityInterpretation?.overall || '数据不足，无法进行能力分析。' }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 参数详情和过程能力分析 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :sm="12" :md="12">
        <el-card shadow="hover" class="param-card">
          <div slot="header" class="card-header">
            <span>参数详情</span>
          </div>
          <el-descriptions :column="1" border size="medium">
            <el-descriptions-item label="参数名称">{{ capabilityData.capability?.paramName || '--' }}</el-descriptions-item>
            <el-descriptions-item label="规格上限 (USL)">{{ capabilityData.capability?.usl || '--' }}</el-descriptions-item>
            <el-descriptions-item label="规格下限 (LSL)">{{ capabilityData.capability?.lsl || '--' }}</el-descriptions-item>
            <el-descriptions-item label="目标值 (Target)">{{ capabilityData.capability?.target || '--' }}</el-descriptions-item>
            <el-descriptions-item label="样本数量">{{ capabilityData.capability?.sampleSize || '--' }}</el-descriptions-item>
            <el-descriptions-item label="平均值">{{ capabilityData.capability?.avg || '--' }}</el-descriptions-item>
            <el-descriptions-item label="标准差">{{ capabilityData.capability?.stdDev || '--' }}</el-descriptions-item>
            <el-descriptions-item label="最大值">{{ capabilityData.capability?.max || '--' }}</el-descriptions-item>
            <el-descriptions-item label="最小值">{{ capabilityData.capability?.min || '--' }}</el-descriptions-item>
            <el-descriptions-item label="超规范率">{{ (capabilityData.capability?.outOfSpecRate || 0) + '%' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="card-header">
            <span>测量数据分布</span>
          </div>
          <div class="chart-container" ref="distributionChart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 过程能力解读和建议 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>过程能力解读与建议</span>
          </div>
          <div class="interpretation-content">
            <el-alert
              :type="getAlertType"
              :title="getAlertTitle"
              :description="getAlertDescription"
              show-icon
              :closable="false">
            </el-alert>
            
            <div class="tips-section" v-if="hasSuggestions">
              <h4>改进建议:</h4>
              <el-divider></el-divider>
              <div class="tips-content">
                <ul>
                  <li v-if="isCpLow">
                    <b>提高Cp值:</b> 减小过程波动，优化工艺参数，应用SPC控制手段，提高设备精度和稳定性。
                  </li>
                  <li v-if="isCpkLow && !isCpLow">
                    <b>提高Cpk值:</b> 调整过程平均值，使其接近目标值中心。检查并校准设备，调整工艺参数。
                  </li>
                  <li v-if="isOutOfSpec">
                    <b>降低超规范率:</b> 实施严格的过程控制，定期检查和维护设备，加强操作人员培训。
                  </li>
                  <li v-if="hasHighVariation">
                    <b>降低变异:</b> 识别并消除特殊原因变异，应用统计过程控制和预防性维护。
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: "ProcessCapabilityAnalysis",
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    queryParams: {
      type: Object,
      required: true
    },
    capabilityData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      distributionChart: null
    }
  },
  computed: {
    getCpClass() {
      const cp = this.capabilityData.capability?.cp;
      if (!cp) return '';
      if (cp >= 1.67) return 'text-excellent';
      if (cp >= 1.33) return 'text-good';
      if (cp >= 1.0) return 'text-adequate';
      return 'text-poor';
    },
    getCpkClass() {
      const cpk = this.capabilityData.capability?.cpk;
      if (!cpk) return '';
      if (cpk >= 1.67) return 'text-excellent';
      if (cpk >= 1.33) return 'text-good';
      if (cpk >= 1.0) return 'text-adequate';
      return 'text-poor';
    },
    getAlertType() {
      const cp = this.capabilityData.capability?.cp;
      const cpk = this.capabilityData.capability?.cpk;
      
      if (!cp || !cpk) return 'info';
      if (cp >= 1.33 && cpk >= 1.33) return 'success';
      if (cp >= 1.0 || cpk >= 1.0) return 'warning';
      return 'error';
    },
    getAlertTitle() {
      const cp = this.capabilityData.capability?.cp;
      const cpk = this.capabilityData.capability?.cpk;
      
      if (!cp || !cpk) return '数据不足';
      if (cp >= 1.33 && cpk >= 1.33) return '过程能力优良';
      if (cp >= 1.33 && cpk < 1.33) return '过程能力良好，但偏离中心';
      if (cp < 1.33 && cpk >= 1.0) return '过程能力一般，需改进';
      return '过程能力不足，需优化';
    },
    getAlertDescription() {
      return this.capabilityData.capabilityInterpretation?.overall || 
             '过程能力分析是评估生产过程满足规格要求的能力，Cp反映过程离散程度，Cpk反映过程中心与目标的偏移度。';
    },
    isCpLow() {
      const cp = this.capabilityData.capability?.cp;
      return cp && cp < 1.33;
    },
    isCpkLow() {
      const cpk = this.capabilityData.capability?.cpk;
      return cpk && cpk < 1.33;
    },
    isOutOfSpec() {
      const outOfSpecRate = this.capabilityData.capability?.outOfSpecRate;
      return outOfSpecRate && outOfSpecRate > 0.0027; // 超过3sigma
    },
    hasHighVariation() {
      const stdDev = this.capabilityData.capability?.stdDev;
      const avg = this.capabilityData.capability?.avg;
      return stdDev && avg && (stdDev / avg) > 0.1; // 10%的变异系数
    },
    hasSuggestions() {
      return this.isCpLow || this.isCpkLow || this.isOutOfSpec || this.hasHighVariation;
    }
  },
  watch: {
    'capabilityData': {
      handler() {
        this.$nextTick(() => {
          this.initDistributionChart();
        });
      },
      deep: true
    },
    'loading': {
      handler(newVal) {
        if (!newVal) {
          this.$nextTick(() => {
            this.initDistributionChart();
          });
        }
      }
    }
  },
  mounted() {
    this.initDistributionChart();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    this.disposeCharts();
  },
  methods: {
    resizeCharts() {
      this.distributionChart?.resize();
    },
    disposeCharts() {
      this.distributionChart?.dispose();
    },
    initDistributionChart() {
      if (!this.$refs.distributionChart) return;
      
      if (this.distributionChart) {
        this.distributionChart.dispose();
      }
      
      this.distributionChart = echarts.init(this.$refs.distributionChart);
      
      const measurementDistribution = this.capabilityData.measurementDistribution || [];
      if (measurementDistribution.length === 0) {
        this.distributionChart.setOption({
          title: {
            text: '没有测量数据',
            left: 'center',
            top: 'middle',
            textStyle: {
              fontSize: 16,
              color: '#999'
            }
          }
        });
        return;
      }
      
      // 提取数据
      const xData = measurementDistribution.map(item => parseFloat(item.binCenter));
      const freqData = measurementDistribution.map(item => item.frequency);
      
      // 读取规格限和其他参数
      const capability = this.capabilityData.capability || {};
      const usl = capability.usl;
      const lsl = capability.lsl;
      const target = capability.target;
      const avg = capability.avg;
      
      // 生成更加分散的散点数据
      const scatterData = [];
      xData.forEach((x, index) => {
        const frequency = freqData[index];
        
        // 对于每个频数，生成对应数量的散点，稍微随机分布在x值附近
        for (let i = 0; i < frequency; i++) {
          // 在x值附近添加随机偏移，使点更分散
          const xOffset = (Math.random() - 0.5) * 0.2; // 添加±0.1的随机偏移
          const yPosition = i + 1; // 垂直堆叠点
          
          scatterData.push([x + xOffset, yPosition]);
        }
      });
      
      // 创建图表配置
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            return `测量值: ${params.data[0].toFixed(2)}`;
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '测量值',
          nameLocation: 'middle',
          nameGap: 30
        },
        yAxis: {
          type: 'value',
          name: '频数',
          nameRotate: 90,
          nameLocation: 'middle',
          nameGap: 30,
          axisLabel: {
            formatter: function(value) {
              return value === 0 ? '0' : '';
            }
          }
        },
        series: [
          {
            name: '测量数据分布',
            type: 'scatter',
            data: scatterData,
            symbolSize: 8,
            itemStyle: {
              color: '#5470c6'
            },
            markLine: {
              silent: true,
              data: []
            }
          }
        ]
      };
      
      // 添加标记线，确保数据有效
      if (usl !== undefined && usl !== null && !isNaN(usl)) {
        option.series[0].markLine.data.push({
          name: 'USL',
          xAxis: parseFloat(usl),
          lineStyle: { color: '#f56c6c', width: 2 },
          label: { show: true, position: 'end' }
        });
      }
      
      if (lsl !== undefined && lsl !== null && !isNaN(lsl)) {
        option.series[0].markLine.data.push({
          name: 'LSL',
          xAxis: parseFloat(lsl),
          lineStyle: { color: '#f56c6c', width: 2 },
          label: { show: true, position: 'end' }
        });
      }
      
      if (target !== undefined && target !== null && !isNaN(target)) {
        option.series[0].markLine.data.push({
          name: 'Target',
          xAxis: parseFloat(target),
          lineStyle: { color: '#67c23a', width: 2 },
          label: { show: true, position: 'end' }
        });
      }
      
      if (avg !== undefined && avg !== null && !isNaN(avg)) {
        option.series[0].markLine.data.push({
          name: 'Avg',
          xAxis: parseFloat(avg),
          lineStyle: { color: '#409EFF', width: 2 },
          label: { show: true, position: 'end' }
        });
      }
      
      this.distributionChart.setOption(option);
    }
  }
}
</script>

<style scoped>
.process-capability-analysis {
  padding: 10px 0;
}
.capability-card {
  margin-bottom: 20px;
}
.capability-item {
  text-align: center;
  padding: 10px 0;
}
.item-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
.item-value {
  font-size: 30px;
  font-weight: bold;
}
.item-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
  text-align: left;
  padding: 0 10px;
}
.text-excellent {
  color: #67c23a;
}
.text-good {
  color: #409EFF;
}
.text-adequate {
  color: #e6a23c;
}
.text-poor {
  color: #f56c6c;
}
.chart-row {
  margin-bottom: 20px;
}
.chart-card, .param-card {
  height: 100%;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chart-container {
  height: 300px;
  width: 100%;
}
.interpretation-content {
  padding: 10px;
}
.tips-section {
  margin-top: 20px;
}
.tips-content {
  padding: 10px;
}
</style> 